package by.jabbby.ui.act;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import by.jabbby.JabbbyException;
import by.jabbby.Logger;
import by.jabbby.dataprovider.AccountProvider;
import by.jabbby.dataprovider.ChatEntry;
import by.jabbby.dataprovider.ChatProvider;
import by.jabbby.service.JabberService;
import by.jabbby.service.JabberServiceProxy;

public class Chat extends TitleBar {

	//private JabberServiceProxy jabberProxy;
	private String chatJid;
	private TextView messagesTextView;
	String currentAccount;
//	private MainMenuUtil menuUtil;

	BroadcastReceiver messageListener = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			
			if (JabberService.ACTION_NEW_MESSAGE.equals(intent.getAction())) {
				String from = (String) intent.getExtras().get(JabberService.ACTION_NEW_MESSAGE_CHAT);
				String msg = (String) intent.getExtras().get(JabberService.ACTION_NEW_MESSAGE_BODY);
				ChatEntry ce = new ChatEntry(msg, from, currentAccount);
				Chat.this.writeMessageAndScroll(ce);
			}

		}
	};

	public void onCreate(Bundle intent) {
		try {
			super.onCreate(intent);
		//	jabberProxy = JabberServiceProxy.getInstance(this);
		
		//	menuUtil = new MainMenuUtil(this, jabberProxy);
			AccountProvider accountProvider = new AccountProvider(this.getApplicationContext());
			currentAccount = accountProvider.getCurrentAccount().getConnectionString();
			
			this.setContentView(R.layout.chat);
			this.initTitleBar();
			
			chatJid = this.getIntent().getStringExtra("by.jabbby.ui.act.user_jid");
			
			if(jabberProxy.isServiceBinded()){
		//		jabberProxy.getService().activeChat(chatJid);
				initChatView();
			}
			// getWindow().
			// registerRecivers();
			// jabberProxy = new JabberServiceProxy(this);
			// menuUtil = new MainMenuUtil(this, jabberProxy);
			// setContentView(R.layout.rosters);
			
			
			// getWindow().setTitle("Title of window");
		} catch (Exception e) {
			Logger.e(e);
		}

	}

	protected void initChatView() {
		try {

			Button sendBtn = (Button) this.findViewById(R.id.sendMsgBtn);
			// EditText text = (EditText) this.findViewById(R.id.sendTextET);
			messagesTextView = (TextView) this.findViewById(R.id.chat_messages);
			// ApplicationPreference.

			ChatProvider cp = new ChatProvider(currentAccount, this.getApplicationContext());
			List<ChatEntry> entries = cp.getEntries(chatJid, currentAccount);
			for (ChatEntry ce : entries) {
				writeMessage(ce);
			}
			scrollMessages();
			LinearLayout ll = (LinearLayout) findViewById(R.id.MessagesLayout);
			if (jabberProxy.getService().isConnected()) {
				sendBtn.setOnClickListener(new View.OnClickListener() {

					public void onClick(View paramView) {
						try {
							EditText text = (EditText) Chat.this.findViewById(R.id.sendTextET);

							String msgTxt = text.getText().toString();
							jabberProxy.getService().sendMessage(chatJid, msgTxt);
							ChatEntry ce = new ChatEntry(msgTxt, currentAccount, chatJid);
							Chat.this.writeMessageAndScroll(ce);
						} catch (Exception e) {
							Logger.e("Chat error when send message", e);
							//e.printStackTrace();
						}
					}
				});
				ll.setVisibility(View.VISIBLE);

			} else {
				ll.setVisibility(View.INVISIBLE);
			}

		} catch (Exception e) {
			Logger.e(e);
		}

	}

	private void writeMessage(ChatEntry ce) {
		messagesTextView.append("\n");
		if (ce.getDate() != null) {
			
			messagesTextView.append(DateFormat.format(Primary.DATE_FORMAT, ce.getDate()) );
			
		}
		if (ce.getFrom() != null) {
			messagesTextView.append("  ");
			messagesTextView.append(ce.getFrom());
			messagesTextView.append("\n");
		}
		if (ce.getMessage() != null) {
			messagesTextView.append(ce.getMessage());
			messagesTextView.append("\n");
		}

	}

	private void writeMessageAndScroll(ChatEntry ce) {
		writeMessage(ce);
		scrollMessages();
	}

	private ScrollView getMessagesScroll() {
		ScrollView sv = (ScrollView) findViewById(R.id.chat_messages_scroll);
		return sv;
	}

	private void scrollMessages() {
		getMessagesScroll().post(new Runnable() {
			public void run() {
				getMessagesScroll().fullScroll(ScrollView.FOCUS_DOWN);
			}
		});
	}

	

	@Override
	protected void onDestroy() {
		// unRegisterRecivers();
		super.onDestroy();

	}

	@Override
	protected void onPause() {
		super.onPause();
	//	 unRegisterRecivers();
		unRegisterMessageRecivers();
		
	}

	@Override
	protected void onRestart() {
		// unRegisterRecivers();
		// registerRecivers();
		super.onRestart();
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// registerRecivers();
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onResume() {
		// registerRecivers();
		super.onResume();
	}

	protected void registerMessageReciver() {
		IntentFilter intent = new IntentFilter();
		intent.addAction(JabberService.ACTION_NEW_MESSAGE);
		if (messageListener == null) {
			messageListener = new BR();
		}
		this.registerReceiver(messageListener, intent);

	}

	protected void unRegisterMessageRecivers() {

		if (messageListener != null) {
			this.unregisterReceiver(messageListener);
		}

	}
	@Override
	protected void onStart(){
		super.onStart();
		registerMessageReciver();
		getLeftTextView().setText(this.chatJid);
		if(jabberProxy.isServiceBinded()){
			try {
				jabberProxy.getService().activeChat(chatJid);
			} catch (Exception e) {
				Logger.e(e);
			} 
			initChatView();
		}
	}

	public void onJabberServiceBinded() {
		super.onJabberServiceBinded();
		initChatView();
		try {
			jabberProxy.getService().activeChat(chatJid);
		} catch (Exception e) {
			Logger.e(e);
		} 
		
	}

}
